package cn.wolfcode.p2p.controller;

import cn.wolfcode.p2p.base.domain.IpLog;
import cn.wolfcode.p2p.base.domain.LoginInfo;
import cn.wolfcode.p2p.base.exception.CustomException;
import cn.wolfcode.p2p.base.service.IIpLogService;
import cn.wolfcode.p2p.base.service.ILoginInfoService;
import cn.wolfcode.p2p.util.JSONResult;
import cn.wolfcode.p2p.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class MgrSiteLoginController {
        @Autowired
        private ILoginInfoService loginInfoService;
        @Autowired
        private IIpLogService ipLogService;

        @RequestMapping("login")
        @ResponseBody
        public JSONResult login(LoginInfo loginInfo){
                JSONResult jsonResult = new JSONResult();
                int state= IpLog.STATE_FAIL;
                try {
                        loginInfoService.login(loginInfo,LoginInfo.TYPE_MGRSITE);
                        state=IpLog.STATE_SUCCESS;
                }catch (CustomException e ){
                        jsonResult.setMsg(e.getMessage());//自定义的异常,避免所有异常都返回同样的信息给客户
                } catch (Exception e) {
                        e.printStackTrace();
                        jsonResult.setMsg("系统繁忙,请稍后再试");
                }
                ipLogService.save(loginInfo.getUsername(),state,LoginInfo.TYPE_MGRSITE);
                return jsonResult;
        }

        @RequestMapping("logout")
        @ResponseBody
        public JSONResult logout(){
                UserContext.getSession().invalidate();
                return new JSONResult();
        }


}
